import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/open_live_current_good_event.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/stream/dialog/delete_word_dialog.dart';
import 'package:star_author/views/stream/dialog/last_backflow_good_info.dart';
import 'package:star_author/views/stream/model/live_good_list_entity.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/dialog/get_dialog.dart';
import 'package:star_author/widgets/image_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'select_evaluate_dialog.dart';

class ScanResultDialog extends StatefulWidget {
  String searchText;
  Map studioDetail;
  late RtcEngine? engine;
  Function? muteCallBack;
  LiveGoodListData data;
  bool isStartExplain; //是否讲解中
  ScanResultDialog({
    Key? key,
    required this.searchText,
    required this.studioDetail,
    required this.engine,
    required this.muteCallBack,
    required this.data,
    this.isStartExplain: false,
  }) : super(key: key);

  @override
  State<ScanResultDialog> createState() => _ScanResultDialogState();
}

class _ScanResultDialogState extends State<ScanResultDialog> {
  LiveGoodListData data = LiveGoodListData();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    data = widget.data;
  }

  buildLeftWidget() {
    //是否转回流 转回流显示转回流
    if (data.last_history_backflow != null) {
      return BackflowGoodWidget(
        param: data.last_history_backflow,
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      width: Get.width,
      constraints: BoxConstraints(
        minHeight: 100.w,
        maxHeight: 300.w,
      ),
      child: SafeArea(
        child: Stack(
          children: [
            Positioned(
              child: GestureDetector(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: RoucesUtil.getAssetsIcon('lt_common/clear', 14.w),
                  padding: EdgeInsets.only(
                    left: 12.w,
                    right: 12.w,
                    top: 14.w,
                  ),
                ),
                onTap: () {
                  Get.back();
                },
                behavior: HitTestBehavior.opaque,
              ),
              top: 0.w,
              right: 0.w,
            ),
            Container(
              margin: EdgeInsets.only(
                left: 12.w,
                right: 12.w,
                top: 20.w,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Center(
                    child: Text(
                      "扫码货品",
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: rgba(51, 51, 51, 1),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 18.w,
                  ),
                  Container(
                    child: Row(
                      children: [
                        ClipRRect(
                          child: ImageWithPlaceHolder(
                            cover: data.goods?.cover?.url ?? "",
                            width: 128.w,
                            height: 128.w,
                            radius: 4.w,
                          ),
                          borderRadius: BorderRadius.circular(
                            4.w,
                          ),
                        ),
                        SizedBox(
                          width: 10.w,
                        ),
                        Expanded(
                          child: Container(
                            height: 128.w,
                            child: buildContent(),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 30.w,
                  ),
                  buildButton(),
                  SizedBox(
                    height: 20.w,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildContent() {
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start;
    if (data.last_history_backflow != null) {
      mainAxisAlignment = MainAxisAlignment.spaceBetween;
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: mainAxisAlignment,
      children: [
        Text(
          data.goods?.title ?? "",
          style: TextStyle(
            fontSize: 16.sp,
            color: rgba(51, 51, 51, 1),
            fontWeight: FontWeight.w500,
          ),
        ),
        if ((data.anchorEvaluationPriceRange ?? []).length > 0)
          Container(
            child: Row(
              children: [
                Text(
                  "主播${data.anchor_nickname ?? ""}",
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: rgba(153, 153, 153, 1),
                  ),
                ),
                SizedBox(
                  height: 8.w,
                ),
                Text(
                  getPriceWithList(
                    data.anchorEvaluationPriceRange ?? [],
                    intl: true,
                  ),
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: rgba(153, 153, 153, 1),
                  ),
                ),
              ],
            ),
            margin: EdgeInsets.only(
              top: 10.w,
            ),
          ),
        if ((data.priceRange ?? []).length > 0)
          Container(
            margin: EdgeInsets.only(
              top: 10.w,
            ),
            child: Row(
              children: [
                Text(
                  "最终估价",
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: rgba(153, 153, 153, 1),
                  ),
                ),
                SizedBox(
                  height: 8.w,
                ),
                Text(
                  getPriceWithList(
                    data.priceRange ?? [],
                    intl: true,
                  ),
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: rgba(224, 32, 32, 1),
                  ),
                ),
              ],
            ),
          ),
        if (data.last_history_backflow != null) buildLeftWidget(),
      ],
    );
  }

  buildButton() {
    if (widget.isStartExplain) {
      return ButtonWidget(
        child: Text(
          "选择估价",
          style: TextStyle(
            fontSize: 16.sp,
            color: rgba(254, 186, 7, 1),
            fontWeight: FontWeight.w500,
          ),
        ),
        type: ButtonType.bdYellow,
        onPressed: () {
          Get.back();
          //选择估价
          Get.bottomSheet(
            SelectEvaluateDialog(
              searchText: "",
              studioDetail: widget.studioDetail,
              engine: widget.engine,
              data: widget.data,
              muteCallBack: widget.muteCallBack,
              select_reference: {},
            ),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(
                top: Radius.circular(16.w),
              ),
            ),
            barrierColor: Colors.transparent,
            isScrollControlled: true,
          );
        },
      );
    }
    if ((widget.data.anchorEvaluationPriceRange?.length ?? 0) > 0 &&
        (data.recordingVideo ?? "").isNotEmpty) {
      return Container();
    }
    if ((data.recordingVideo ?? "").isNotEmpty) {
      return ButtonWidget(
        child: Text(
          "删除录播",
          style: TextStyle(
            fontSize: 16.sp,
            color: rgba(51, 51, 51, 1),
            fontWeight: FontWeight.w500,
          ),
        ),
        type: ButtonType.bdNormal,
        onPressed: () {
          showGetDialog(DeleteRecordingDialog(
            delete: () async {
              HttpUtil.commonRequest(
                Get.context!,
                '/api/v1/backflows/${data.id}/detach_recording_video',
                method: HttpUtil.MethodPut,
                data: {
                  "anchor_id": MediaRecorderUtil.anchorId,
                },
              ).then((value) {
                data.recordingVideo = "";
                data.anchor_nickname = "";
                data.anchorEvaluationPriceRange = [];
                data.priceRange = [];
                setState(() {});
              });
            },
          ));
        },
      );
    } else {
      return ButtonWidget(
        child: Text(
          "开始讲解",
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        type: ButtonType.bgOrange,
        onPressed: () {
          List<Map> list =
              SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
          int index = list.indexWhere(
              (element) => element['id'].toString() == data.id.toString());
          if (index == -1) {
            list.add({
              ...data.toJson(),
              "anchorId": MediaRecorderUtil.anchorId,
              "liveName": widget.studioDetail['name'] ?? "",
              "anchorName":
                  widget.studioDetail['living_anchor']['nickname'] ?? "",
              "isAgree": true,
            });
          }
          MediaRecorderUtil.stopRecording();
          SpUtil.putObjectList(MediaRecorderUtil.localKey, list);
          HttpUtil.commonRequest(Get.context!,
                  '/api/v1/studios/${StreamConf.liveId}/start_explaining',
                  queryParameters: {
                    "backflow_id": data.id,
                  },
                  method: HttpUtil.MethodPut)
              .then((value) {
            if (value.statusCode == 200) {
              //当我们服务器请求成功才开始录制 不然网络不好的时候会多录制一些脏数据
              widget.engine?.muteLocalAudioStream(false);
              if (widget.muteCallBack != null) {
                widget.muteCallBack!();
              }
              MediaRecorderUtil.startRecording(data.id ?? 0);
              CustomToast.show("已切换所讲解的货品");
              GlobalEventBus().bus.fire(OpenLiveCurrentGoodEvent(data));
              RongUtil.operation(OperationKey.start_explain, {});
              Get.back();
            }
          });
        },
      );
    }
  }
}
